package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.qk.domain.business.BusinessCountDO;
import com.qk.domain.clue.ClueCountDO;
import com.qk.vo.homePage.HomePageVO;
import com.qk.management.mapper.BusinessMapper;
import com.qk.management.mapper.ClueMapper;
import com.qk.management.service.HomePageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/*
 *  @author SHCJ
 *  @created 2025/10/16 11:26
 *  @description
 */
@Service
public class HomePageServiceImpl implements HomePageService {
    private static final String CACHE_PORTAL_KEY_PREFIX = "qk:portal:";
    @Autowired
    private ClueMapper clueMapper;

    @Autowired
    private BusinessMapper businessMapper;

    //        创建redis对象
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public HomePageVO homePage() {
        ClueCountDO clueCountDO = this.clueMapper.selectCountClue();
        BusinessCountDO businessCountDO = this.businessMapper.selectCountBusiness();
        HomePageVO homePageVO = BeanUtil.copyProperties(clueCountDO, HomePageVO.class);
        BeanUtil.copyProperties(businessCountDO, homePageVO);
        return homePageVO;
    }

    @Override
    public HomePageVO homePageByRedis() {

        String redisKey = CACHE_PORTAL_KEY_PREFIX + "homePage";
        String json = stringRedisTemplate.opsForValue().get(redisKey);
        try {
            if(ObjectUtil.isNotEmpty( json)){
                return JSONUtil.toBean(json, HomePageVO.class);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


//        如果redis没有缓存
        ClueCountDO clueCountDO = this.clueMapper.selectCountClue();
        BusinessCountDO businessCountDO = this.businessMapper.selectCountBusiness();
        HomePageVO homePageVO = BeanUtil.copyProperties(clueCountDO, HomePageVO.class);
        BeanUtil.copyProperties(businessCountDO, homePageVO);


        try {
//        查询完把数据存到redis中
            stringRedisTemplate.opsForValue().set(redisKey, JSONUtil.toJsonStr(homePageVO));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return homePageVO;
    }


}
